package com.reconcile.phone.common.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 功能描述:
 *
 * @author zxl
 * @since 2024/6/20
 */
public class InvitationCodeGenerator {

  public static String generateInvitationCode(String userId) {
    try {
      MessageDigest md = MessageDigest.getInstance("SHA-256");
      byte[] hash = md.digest(userId.getBytes());
      // 转换成64位的hash码
      String hashString = bytesToHex(hash);
      // 取hash码的前6位数字
      String invitationCode = hashString.substring(0, 6);
      // 补零确保长度为6位
      return String.format("%6s", invitationCode).replace(' ', '0');
    } catch (NoSuchAlgorithmException e) {
      throw new RuntimeException(e);
    }
  }

  private static String bytesToHex(byte[] bytes) {
    StringBuilder hexString = new StringBuilder();
    for (byte b : bytes) {
      String hex = Integer.toHexString(0xff & b);
      if (hex.length() == 1) {
        hexString.append('0');
      }
      hexString.append(hex);
    }
    return hexString.toString();
  }

}
